<template>
  <j-modal
    :width="width"
    :visible="visible"
    switchFullscreen
    @ok="handleCancel"
    :okButtonProps="{ class: { 'jee-hidden': disableSubmit } }"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <template slot="title"> 平台仓导入<span class="title">批量导入平台仓库</span> </template>
    <a-row class="row">
        <a-upload
          name="file"
          :showUploadList="false"
          :multiple="false"
          :headers="tokenHeader"
          :action="importExcelUrl"
          @change="handleImportExcel"
        >
          <a-button type="primary">上传文件</a-button>
        </a-upload>
        <div><a @click="handleExportXls('鸿展WMS平台仓导入模板',url.downloadPlatformTemplate)">下载模板</a></div>
    </a-row>
    <a-row class="row2" v-if="fileName">
      <span>{{fileName}}</span> <a><a-icon type="close-circle"  @click="fileName=''" /></a>
    </a-row>
    <div class="tip">
        <a>1.仅支持xls文件导入</a>
        <a>2.每次仅允许导入一个文件</a>
        <a>3.若有已上传文件，新上传文件将替换已上传文件</a>
    </div>
  </j-modal>
</template>
  
  <script>
import Vue from 'vue'
import { ACCESS_TOKEN, TENANT_ID } from '@/store/mutation-types'
import { deleteAction, getAction,downFile,getFileAccessHttpUrl } from '@/api/manage'
export default {
  name: 'WarehouseImportModal',
  data() {
    return {
      title: '',
      width: 700,
      visible: false,
      disableSubmit: false,
      fileName:'',   //上传文件名
      url: {
        importExcelUrl: 'wms/warehouse/importPlatform',
        downloadPlatformTemplate: "wms/warehouse/downloadPlatformTemplate",
      },
    }
  },
  computed: {
    //token header
    tokenHeader() {
      let head = { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) }
      let tenantid = Vue.ls.get(TENANT_ID)
      if (tenantid) {
        head['tenant-id'] = tenantid
      }
      return head
    },
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    add() {
      this.fileName = ''
      this.visible = true
    },
    edit(record) {
      this.visible = true
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {},
    submitCallback() {
      this.$emit('ok')
      this.visible = false
    },
    handleCancel() {
      this.$emit('ok')
      this.visible = false
    },
    //下载模板
    handleExportXls(fileName, templateUrl, params, callback){
      if(!fileName || typeof fileName != "string"){
        fileName = "导出文件"
      }
      let exportXlsUrl;
      if(templateUrl === 'template'){
        exportXlsUrl = this.url.exportTemplateXlsUrl;
      }else if(templateUrl && templateUrl != 'template'){
        exportXlsUrl = templateUrl;
      }else{
        exportXlsUrl = this.url.exportXlsUrl;
      }
      downFile(exportXlsUrl,{}).then((data)=>{
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (data.type === 'application/json') {
          this.blobToJson(data).then((res) => {
            this.$message.warning(res.message)
          })
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName+'.xlsx')
        }else{
          let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          if (exportXlsUrl.indexOf("/flowable/") !== -1){
            link.setAttribute('download', fileName+'.xls')
          }else {
            link.setAttribute('download', fileName+'.xlsx')
          }
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      }).finally(() => {
        callback && callback();
      })
    },
    /* 导入 */
    handleImportExcel(info) {
      this.loading = true
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        this.loading = false  
        if (info.file.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let {
              message,
              result: { msg, fileUrl, fileName },
            } = info.file.response
            this.$warning({
              title: message,
              content: (
                <div>
                  <span>{msg}</span>
                  <br />
                  <span>
                    具体详情请{' '}
                    <a href={fileUrl} target="_blank" download={fileName}>
                      点击下载
                    </a>{' '}
                  </span>
                </div>
              ),
            })
          } else {
            this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
            this.fileName = info.file?.name || ''
          }
          //this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`)
        }
      } else if (info.file.status === 'error') {
        this.loading = false
        if (info.file.response.status === 500) {
          let data = info.file.response
          const token = Vue.ls.get(ACCESS_TOKEN)
          if (token && data.message.includes('Token失效')) {
            this.$error({
              title: '登录已过期',
              content: '很抱歉，登录已过期，请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  window.location.reload()
                })
              },
            })
          }
        } else {
          this.$message.error(`文件上传失败: ${info.file.msg} `)
        }
      }
    },
  },
}
</script>
  <style lang="less" scoped>
.title {
  font-size: 14px;
  color: #0000006d;
  margin-left: 5px;
}
.row {
    display: flex;
    align-items: self-end;
  a {
    margin-left: 20px;
    color: #1e5af9;
  }
}
.row2{
    margin-top: 10px;
    span{
      color: #1E98D7;
      margin-right: 5px;
    }
    a{
      color: rgba(0,0,0,.45);
    }
}
.tip{
    width: 100%;
    border-radius: 5px;
    background: #EEF7FF;
    padding:4px 10px;
    margin-top: 10px;
    a{
      color: #1890FF;
      display: block;
      margin: 5px 0;
      font-size: 13px;
    }
}
</style>